package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ccj.poptabview.FilterConfig;
import com.ccj.poptabview.PopTabView;
import com.ccj.poptabview.base.BaseFilterTabBean;
import com.ccj.poptabview.bean.FilterGroup;
import com.ccj.poptabview.bean.FilterTabBean;
import com.ccj.poptabview.listener.OnPopTabSetListener;
import com.ccj.poptabview.loader.PopEntityLoaderImp;
import com.ccj.poptabview.loader.ResultLoaderImp;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ExpertNewVO;
import com.digitalchina.lxnsy.entity.MyExpertVO;
import com.digitalchina.lxnsy.entity.OrganizationsVO;
import com.digitalchina.lxnsy.entity.SearchTypeVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.viewholder.AddMyExpertsListHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;

/**
 * 添加我的专家 Created by zhy on 2018/1/13 0013.
 */

public class AddMyExpertsActivity extends BaseActivity
        implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, OnPopTabSetListener, AddMyExpertsListHolder.AddExpertListener {
    @Bind(R.id.tv_search)
    EditText tvSearch;
    @Bind(R.id.expand_pop)
    PopTabView expandPop;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.confirm_add)
    TextView confirmAdd;
    @Bind(R.id.iv_cancel)
    ImageView ivCancel;

    private RecyclerArrayAdapter adapter;

    private int page = 1;
    private int limit = 10;
    private List<ExpertNewVO> voList = new ArrayList<>();
    private List<ExpertNewVO> addList = new ArrayList<>();  //添加集合
    private String keywords = "";
    private String eClassCode = "";
    private String rDirectCode = "";
    private String sortType = "";
    private String orgID = "";
    private MyExpertVO expertNewVO;

    private StringBuffer expertIds = new StringBuffer();
    // 1级分类
    private List<SearchTypeVO> list = new ArrayList<>();
    // 机构
    private List<OrganizationsVO> organizationsList = new ArrayList<>();


    Map<String, Object> map = new HashMap<>();

    private int addCount = 0;
    private boolean fromMyExpert;   //是否从我的专家过来

    @Override
    public void setLayout() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentLayout(R.layout.activity_add_my_experts);
        setTitle("添加我的专家");
    }

    @Override
    public void initMember() {
        // 产品分类
        BusinessExpert.myExpertSearchType(this, mHandler);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new AddMyExpertsListHolder(parent, AddMyExpertsActivity.this, addCount);
            }
        });
        if (null != getIntent()) {
            addCount = getIntent().getIntExtra("addCount", 0);
        }
        map = (Map<String, Object>) getIntent().getSerializableExtra("map");
        fromMyExpert = getIntent().getBooleanExtra("fromMyExpert", false);
        if (null != map)
            expertNewVO = (MyExpertVO) map.get("MyExpertVO");
        if (null != expertNewVO)
            orgID = expertNewVO.getId();
        onRefresh();
    }

    private void searchList() {
        /**
         * 搜索添加我的专家专家搜索
         *
         * @param keywords
         *            关键字
         * @param userAccId
         *            登陆人ID
         * @param eClassCode
         *            专家三级分类
         * @param rDirectCode
         *            专家领域分类
         * @param orgID
         *            组织机构ID
         * @param sortType
         *            排序类型 ： 空 or 0--默认排序 1--推荐专家 2--职称级别
         * @param provinceName
         *            省编码
         * @param cityName
         *            市编码
         * @param page
         *            页码
         * @param limit
         *            条数
         */
//        adapter.clear();
        BusinessExpert.expertDefaultList(this, keywords, eClassCode, rDirectCode, orgID,
                sortType, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    public void addListener() {
        tvSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) textView.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                    }
                    // 刷新列表数据
                    if (!keywords.equals(tvSearch.getText().toString())) {
                        keywords = tvSearch.getText().toString();
                        eClassCode = "";
                        rDirectCode = "";
                        sortType = "";
                        orgID = "";
                        expandPop.setDefaultLabel();
                        searchList();
                    }
                    return true;
                }
                return false;
            }
        });
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keywords = "";
                eClassCode = "";
                rDirectCode = "";
                sortType = "";
                orgID = "";
                expandPop.setDefaultLabel();
                tvSearch.setText("");
                onRefresh();
            }
        });

        confirmAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addList.size() == 0) {
                    showToast("请选择专家");
                    return;
                }
                for (int i = 0; i < addList.size(); i++) {
                    if (addList.size() == 1)
                        expertIds.append(addList.get(i).getUserAccId());
                    else {

                        expertIds.append(addList.get(i).getUserAccId() + ",");
                    }
                }
                if (addList.size() > 1) {
                    expertIds.delete(expertIds.length() - 1, expertIds.length());
                }
                //添加专家
                BusinessExpert.saveMyExpert(AddMyExpertsActivity.this, expertIds.toString(), mHandler);
                expertIds.setLength(0);
            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                Map<String, Object> map = new HashMap<>();
//                map.put("expertTypeVOList", expertTypeVOList);
//                map.put("listList", listList);
                map.put("ExpertVO", adapter.getAllData().get(position));

//                GotoUtil.gotoActivity(ExpertsListActivity.this, AgriculturalExpertsDetailsActivity.class, "map", map);
                GotoUtil.gotoActivity(AddMyExpertsActivity.this, ExpertsDetailActivity.class, "map", map);
//                GotoUtil.gotoActivity(OperateExpertListActivity.this, ExpertsDetailActivity.class);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (recyclerView == null)
                    return;

                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_TECHNOLOGIES_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_TECHNOLOGIES_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_MYEXPERTS_SEARCHTYPE_SUCCESS:
                        setType(msg.obj);
                        break;
                    case MSG.MSG_MYEXPERTS_SEARCHTYPE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_ADD_EXPERTS_SUCCESS:
                        showToast("保存成功");
                        setResult(RESULT_OK);
                        if (null != expertNewVO || fromMyExpert) {
                            GotoUtil.gotoActivity(AddMyExpertsActivity.this, OperateExpertListActivity.class);
                        }
                        finish();
                        break;
                    case MSG.MSG_ADD_EXPERTS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_SEARCH_ADD_EXPERTS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_SEARCH_ADD_EXPERTS_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                }
            }
        };
    }

    private void setType(Object object) {
        list = FastJsonUtil.getListBean(object.toString(), "typeList", SearchTypeVO.class);
        organizationsList = FastJsonUtil.getListBean(object.toString(), "organizations", OrganizationsVO.class);
/*
        if (list != null && list.size() > 0) {

            SearchTypeVO.ResearchFieldTwoStagesBean vo = new SearchTypeVO.ResearchFieldTwoStagesBean();
            vo.setName("全部");
            vo.setCode("");
            List<SearchTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean> vosBeanList = new ArrayList<>();
            SearchTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean vo3 = new SearchTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean();
            vo3.setName("全部分类");
            vo3.setCode("");
            vosBeanList.add(vo3);
            vo.setResearchFieldThreeStageVos(vosBeanList);

            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list.get(i).getResearchFieldTwoStages().size(); j++) {
                    // 单层list所有二级分类
                    list2.add(list.get(i).getResearchFieldTwoStages().get(j));
                }
            }

            list2.add(0, vo);

            FilterGroup filterGroup1 = getMyData1();
            FilterGroup filterGroup2 = getMyData2();
            FilterGroup filterGroup3 = getMyData3();
            FilterGroup filterGroup4 = getMyData4();

            expandPop.setOnPopTabSetListener(this).setPopEntityLoader(new PopEntityLoaderImp())
                    .setResultLoader(new ResultLoaderImp()) // 配置 {筛选类型} 方式
                    .addFilterItem(filterGroup1.getTab_group_name(), filterGroup1.getFilter_tab(),
                            filterGroup1.getTab_group_type(), filterGroup1.getSingle_or_mutiply())
                    .addFilterItem(filterGroup2.getTab_group_name(), filterGroup2.getFilter_tab(),
                            filterGroup2.getTab_group_type(), filterGroup2.getSingle_or_mutiply())
                    .addFilterItem(filterGroup4.getTab_group_name(), filterGroup4.getFilter_tab(),
                            filterGroup4.getTab_group_type(), filterGroup4.getSingle_or_mutiply())
                    .addFilterItem(filterGroup3.getTab_group_name(), filterGroup3.getFilter_tab(),
                            filterGroup3.getTab_group_type(), filterGroup3.getSingle_or_mutiply());
        }*/
    }

    /**
     * 设置第一组筛选器
     *
     * @return
     */
    public FilterGroup getMyData1() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("农产品种");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_LINKED);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        /*for (int i = 0; i < list2.size(); i++) {
            // 一级filter
            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(list2.get(i).getCode());
            singleFilterBean.setTab_name(list2.get(i).getName());

            List<FilterTabBean.ChildTabBean> childFilterList = new ArrayList<>();
            for (int j = 0; j < list2.get(i).getResearchFieldThreeStageVos().size(); j++) {// 二级filter
                FilterTabBean.ChildTabBean secondFilterBean = new FilterTabBean.ChildTabBean();
                secondFilterBean.setTab_id(list2.get(i).getResearchFieldThreeStageVos().get(j).getCode());
                secondFilterBean.setTab_name(list2.get(i).getResearchFieldThreeStageVos().get(j).getName());
                childFilterList.add(secondFilterBean);
            }

            singleFilterBean.setTabs(childFilterList);
            singleFilterList.add(singleFilterBean);
        }*/

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    /**
     * 设置第二组筛选器
     *
     * @return
     */
    public FilterGroup getMyData2() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("服务领域");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        // BaseFilterTabBean
        List<FilterTabBean> singleFilterList = new ArrayList<>();

        /*for (int i = 0; i < list2.size(); i++) {
            // 一级filter
            for (int j = 0; j < list2.get(i).getResearchFieldThreeStageVos().size(); j++) {// 二级filter

                if (list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos() != null)
                    for (int k = 0; k < list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos()
                            .size(); k++) {
                        FilterTabBean singleFilterBean = new FilterTabBean();
                        singleFilterBean.setTab_id(list2.get(i).getResearchFieldThreeStageVos().get(j)
                                .getResearchDirectionVos().get(k).getCode());
                        singleFilterBean.setTab_name(list2.get(i).getName() + "--" + list2.get(i).getResearchFieldThreeStageVos().get(j)
                                .getResearchDirectionVos().get(k).getName());
                        singleFilterList.add(singleFilterBean);
                    }

            }
        }*/

        // 去重
//        Map<String,FilterTabBean> map =new LinkedHashMap<>();
//        for (int i = 0; i < singleFilterList.size(); i++) {
//            FilterTabBean bean = singleFilterList.get(i);
//            if(!map.containsKey(bean.getTab_id())){
//                map.put(bean.getTab_id(),bean);
//            }
//        }
//      List<FilterTabBean> valueList = new ArrayList<>(map.values());

        Set<FilterTabBean> ts = new HashSet<>();
        ts.addAll(singleFilterList);
        List<BaseFilterTabBean> newList = new ArrayList<>();

        newList.addAll(ts);

        filterGroup.setFilter_tab(newList);
        return filterGroup;

    }

    /**
     * 设置第四组筛选器
     *
     * @return
     */
    public FilterGroup getMyData4() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("公共机构");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        for (int i = 0; i < organizationsList.size(); i++) {
            // 一级filter
            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(organizationsList.get(i).getId());
            singleFilterBean.setTab_name(organizationsList.get(i).getName());
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    /**
     * 设置第三组筛选器 0--推荐分类 1--最新 2--最热
     *
     * @return
     */
    public FilterGroup getMyData3() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("默认排序");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        String array[] =
                {"默认排序", "推荐专家", "职称级别"};
        for (int i = 0; i < 3; i++) {// 一级filter

            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(i + "");
            singleFilterBean.setTab_name(array[i]);
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "body", "list", ExpertNewVO.class);

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);

        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onRefresh() {
        /**
         * 添加我的专家专家搜索
         *
         * @param keywords
         *            关键字
         * @param userAccId
         *            登陆人ID
         * @param eClassCode
         *            专家三级分类
         * @param rDirectCode
         *            专家领域分类
         * @param orgID
         *            组织机构ID
         * @param sortType
         *            排序类型 ： 空 or 0--默认排序 1--推荐专家 2--职称级别
         * @param provinceName
         *            省编码
         * @param cityName
         *            市编码
         * @param page
         *            页码
         * @param limit
         *            条数
         */
        page = 1;
        addList = new ArrayList<>();
        BusinessExpert.expertDefaultList(this, keywords, eClassCode, rDirectCode, orgID,
                sortType, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessExpert.expertDefaultList(this, keywords, eClassCode, rDirectCode, orgID,
                    sortType, String.valueOf(page), String.valueOf(limit), mHandler);
        }
    }

    @Override
    public void onPopTabSet(int index, String lable, Object params, String value) {
        keywords = "";
        tvSearch.setText("");
        switch (index) {
            case 0:
                eClassCode = params + "";
                rDirectCode = "";

                if (!StringUtil.isStrEmpty(eClassCode)) {
                    List<BaseFilterTabBean> singleFilterList = new ArrayList<>();


                   /* for (int i = 0; i < list2.size(); i++) {

                        for (int j = 0; j < list2.get(i).getResearchFieldThreeStageVos().size(); j++) {
                            if (eClassCode.equals(list2.get(i).getResearchFieldThreeStageVos().get(j).getCode())) {
                                for (int k = 0; k < list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos().size(); k++) {
                                    FilterTabBean singleFilterBean = new FilterTabBean();
                                    singleFilterBean.setTab_id(list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos().get(k).getCode());
                                    singleFilterBean.setTab_name(list2.get(i).getName() + "--" + list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos().get(k).getName());
                                    singleFilterList.add(singleFilterBean);
                                }
                                break;
                            }
                        }

                    }*/
                    expandPop.removeItem(1, singleFilterList);
                } else {
                    rDirectCode = "";

                    List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

                    /*for (int i = 0; i < list2.size(); i++) {
                        // 一级filter
                        for (int j = 0; j < list2.get(i).getResearchFieldThreeStageVos().size(); j++) {// 二级filter

                            if (list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos() != null)
                                for (int k = 0; k < list2.get(i).getResearchFieldThreeStageVos().get(j).getResearchDirectionVos()
                                        .size(); k++) {
                                    FilterTabBean singleFilterBean = new FilterTabBean();
                                    singleFilterBean.setTab_id(list2.get(i).getResearchFieldThreeStageVos().get(j)
                                            .getResearchDirectionVos().get(k).getCode());
                                    singleFilterBean.setTab_name(list2.get(i).getName() + "--" + list2.get(i).getResearchFieldThreeStageVos().get(j)
                                            .getResearchDirectionVos().get(k).getName());
                                    singleFilterList.add(singleFilterBean);
                                }

                        }
                    }*/

                    Set<BaseFilterTabBean> ts = new HashSet<>();
                    ts.addAll(singleFilterList);
                    List<BaseFilterTabBean> newList = new ArrayList<>();

                    newList.addAll(ts);
                    expandPop.removeItem(1, newList);
                }
                break;
            case 1:
                rDirectCode = params + "";
                break;
            case 2:
                orgID = params + "";
                break;
            case 3:
                sortType = params + "";
                break;
        }
        searchList();
    }

    @Override
    public void addClick(int pos, boolean canCheck) {
        if (!canCheck) {
            showToast("最多只能添加三个专家");
            return;
        }
        ExpertNewVO vo = (ExpertNewVO) adapter.getAllData().get(pos);
        if (vo.isChecked()) {
            vo.setChecked(false);
            addList.remove(vo);
        } else {
            vo.setChecked(true);
            addList.add(vo);
        }
        adapter.getAllData().set(pos, vo);
    }
}
